#include "head.h"

int read_contacts_from_file(const char *filename, AddressBook **head) {
    FILE *file = fopen(filename, "r");
    if (file == NULL) {
        printf("无法打开文件 %s！\n", filename);
        return 0;
    }
    char line[100];
    int count = 0;
    AddressBook *tail = NULL;
    while (fgets(line, sizeof(line), file) != NULL) {
        AddressBook *new_contact = (AddressBook *)malloc(sizeof(AddressBook));
        if (new_contact == NULL) {
            printf("内存分配失败！\n");
            fclose(file);
            return count;
        }
        line[strcspn(line, "\n")] = '\0';
        int sex_int;
        if (sscanf(line, "%d,%[^,],%d,%s", 
                   &new_contact->id, new_contact->name, &sex_int, new_contact->phone) == 4) {
            new_contact->sex = (sex_int == 1) ? WOMAN : MAN;
            new_contact->next = NULL;
            if (*head == NULL) {
                *head = new_contact;
                tail = new_contact;
            } else {
                tail->next = new_contact;
                tail = new_contact;
            }
            count++;
        } else {
            free(new_contact);
        }
    }
    fclose(file);
    return count;
}